package com.credit.mola.app.ui.process.page

import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.credit.mola.app.R
import com.credit.mola.app.databinding.PageFaceBinding
import com.credit.mola.app.pro.ProFragment
import com.credit.mola.app.ui.permission.PermHelper
import com.credit.mola.app.ui.process.activity.CameraFaceActivity
import com.credit.mola.app.ui.process.activity.ProcessActivity
import com.credit.mola.app.utils.config.Configs
import com.credit.mola.app.utils.dialog.PermissionReasonDialog
import com.credit.mola.app.utils.dialog.SubmitSuccessDialog
import com.credit.mola.app.utils.event.EventType
import com.credit.mola.app.utils.event.track.TrackEventManager
import com.credit.mola.app.utils.gilde.ImageUtil
import com.credit.mola.app.utils.http.AppUrls
import com.credit.mola.app.utils.http.AppUrls.addCommonParams
import com.credit.mola.app.utils.http.HttpHelper
import com.credit.mola.app.utils.log.HHLog
import com.credit.mola.lib_baseadapter.SikadwaBaseAdapterUtil.getColor
import com.credit.mola.lib_permission.OnPermissionCallback
import com.credit.mola.lib_permission.Permission
import com.credit.mola.lib_permission.XXPermissions
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/4/23 10:31
 * @Annotation：人脸识别
 */
class FacePage(): ProFragment() {
    private var _binding: PageFaceBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot Face binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    //本地预览地址
    var faceImgPath = ""
    //拍摄的头像地址
    var faceImgUrl = ""

    //是否选中删除信息,默认选中
    private var isSelectedDelete = true

    private var callBack: ((String) -> Unit)? = null
    // 带回调的构造函数
    constructor(callBack: (String) -> Unit) : this() {
        this.callBack = callBack
    }
    companion object {
        fun newInstance(callBack: (String) -> Unit): FacePage {
            return FacePage(callBack)
        }
    }

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageFaceBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        rootViewBinding.containerLayout.setBackgroundColor(ContextCompat.getColor(requireContext(),R.color.transparent))
        isSelectedDelete = true
        showSelectedDeleteViewTips()
        showFaceBeforeView()

        EventBus.getDefault().register(this)
        _binding?.btnSubmitAndStart?.visibility = View.GONE
    }

    override fun initListener() {
        //切换是否选中删除个人信息
        _binding?.faceDeleteTipsLayout?.setOnClickListener {
            isSelectedDelete = !isSelectedDelete
            showSelectedDeleteViewTips()
        }
        _binding?.imgView?.setOnClickListener {
            if (XXPermissions.isGranted(requireContext(), Permission.CAMERA)){
                addEvent(EventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                faceCameraResultLauncher.launch(Intent(context,CameraFaceActivity::class.java))
            } else {
                val item = PermHelper.getCreditMolaCameraItem()
                showCreditMolaPermissionReasonDialog(item)
            }
        }
        //开始 、 提交
        _binding?.btnSubmitAndStart?.setOnClickListener {
            onMolaSubmitFaceDataAction()
        }
    }

    override fun initData() {
        addEvent(EventType.PAGE.PAGE_STEP_FACE_START,"")

        val showApprovedKey1 = getString(R.string.process_face_submit_approved_tips_over)
        val showApprovedKey2 = getString(R.string.process_face_submit_approved_tips_days)
        val showApprovedText = String.format(getString(R.string.process_face_submit_approved_tips),showApprovedKey1,showApprovedKey2)
        val startApprovedIndex1 = showApprovedText.indexOf(showApprovedKey1)
        val startApprovedIndex2 = showApprovedText.indexOf(showApprovedKey2)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.FF00CB48)), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex1, startApprovedIndex1 + showApprovedKey1.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex2, startApprovedIndex2 + showApprovedKey2.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textSelfieApproved?.text = approvedTipsSpannable
    }

    /**
     * 提交人脸数据
     */
    private fun onMolaSubmitFaceDataAction(){
        //开始人脸拍照
        if (faceImgUrl.isEmpty()){
            _binding?.imgView?.callOnClick()
            return
        }
        //提交
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.OCR_INFO)
            put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE）
            put("faceImgUrl",faceImgUrl)//人脸图片
        }
        TrackEventManager.trackEventNow(EventType.CLICK.CLICK_STEP_FACE_CONFIRM_SUBMIT,"")

        //选中删除信息提示
        if (isSelectedDelete){
            showSelfieSubmitDeleteInformationTipsDialog(params)
        } else {
            val act = context as ProcessActivity
            act.submitAction(params)
        }
    }

    private fun showSelectedDeleteViewTips(){
        when(isSelectedDelete){
            true -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_selected)
            }
            else -> {
                _binding?.imgSelected?.setImageResource(R.mipmap.img_orange_normal)
            }
        }
    }

    /**
     * 显示权限说明
     */
    private fun showCreditMolaPermissionReasonDialog(item: JSONObject){
        val requestPermission = item.optString("permission")
        val dialog = PermissionReasonDialog(context,requestPermission,object : PermissionReasonDialog.IDialogCallback{
            override fun onPermissionAgreeClick() {
                HttpHelper.addEvent(EventType.CLICK.CLICK_PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                requestCreditMolaPermission(item)
            }

            override fun onPermissionDenyClick() {
                HttpHelper.addEvent(EventType.CLICK.CLICK_PERMISSION_REASON_DIALOG_DENY,requestPermission)
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.showSikadwaPermissionReason(item)
    }

    /**
     * 申请权限
     */
    private fun requestCreditMolaPermission(item: JSONObject){
        val requestPermission = item.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(requestPermission)
            .request(object:
                OnPermissionCallback {
                override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                    var permissionString = ""
                    p0.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))

                    addEvent(EventType.CLICK.CLICK_STEP_FACE_START_TAKE,"")
                    faceCameraResultLauncher.launch(Intent(context,CameraFaceActivity::class.java))
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEvent(EventType.CLICK.CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(requireContext(),requestPermission)
                }
            })
    }

    /**
     * 提交成功提示
     */
    private fun showSelfieSubmitDeleteInformationTipsDialog(params: JSONObject){
        val sendSuccessDialog = SubmitSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(false)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSubmitSuccess(getString(R.string.process_face_submit_success_tips))

        lifecycleScope.launch {
            delay(1500)
            if (isAdded && !requireActivity().isFinishing && sendSuccessDialog.isShowing) {
                sendSuccessDialog.dismiss()
            }
            delay(200)
            val act = context as ProcessActivity
            act.submitAction(params)
        }
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            FragmentActivity.RESULT_OK -> {
                result.data?.let {
                    faceImgPath = it.getStringExtra("imgLocalPath").toString()
                    faceImgUrl = it.getStringExtra("imgUrl").toString()
                    HHLog.e(">>>>>>>>>Face imgLocalPath：$faceImgPath")
                }
                showFaceAfterView()
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showFaceBeforeView(){
        _binding?.let { binding ->
            binding.imgView.setImageResource(R.mipmap.img_face_default_avater)
            binding.faceMaskView.visibility = View.GONE
            binding.imgFaceReUpload.visibility = View.GONE
            binding.textFaceReTake.visibility = View.GONE
            binding.textFaceTake.visibility = View.VISIBLE
            binding.btnSubmitAndStart.text = getString(R.string.process_face_start)

            callBack?.invoke(faceImgUrl)
        }
    }

    /**
     * 显示拍照之后的View
     */
    private fun showFaceAfterView(){
        _binding?.let { binding ->
            ImageUtil.instance?.loadImageUrl(context, binding.imgView,faceImgPath)
            binding.faceMaskView.visibility = View.VISIBLE
            binding.imgFaceReUpload.visibility = View.VISIBLE
            binding.textFaceReTake.visibility = View.VISIBLE
            binding.textFaceTake.visibility = View.GONE
            binding.btnSubmitAndStart.text = getString(R.string.process_face_submit)

            callBack?.invoke(faceImgUrl)
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    fun onRefreshedProcess(event: String){
        when(event){
            Configs.Event.PROCESS_DATA_SUB -> {//上级点击提交
                onMolaSubmitFaceDataAction()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
        addEvent(EventType.PAGE.PAGE_STEP_FACE_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}